/**
 * 选课相关路由
 */

const express = require('express');
const router = express.Router();
const { db } = require('../db');
const { authenticateToken } = require('./auth');

// 中间件：检查选课权限
const checkEnrollmentAccess = (req, res, next) => {
  const { role, student_id, teacher_id } = req.user;
  const enrollmentId = parseInt(req.params.id);

  // 管理员可以访问所有选课记录
  if (role === 'admin') {
    return next();
  }

  // 学生只能访问自己的选课记录
  if (role === 'student') {
    db.get(
      'SELECT 1 FROM enrollments WHERE id = ? AND student_id = ?',
      [enrollmentId, student_id],
      (err, result) => {
        if (err) {
          return res.status(500).json({ error: '数据库查询错误' });
        }
        if (result) {
          return next();
        }
        res.status(403).json({ error: '无权访问该选课记录' });
      }
    );
    return;
  }

  // 教师可以访问自己课程的选课记录
  if (role === 'teacher') {
    db.get(
      `SELECT 1 FROM enrollments e
       JOIN courses c ON e.course_id = c.id
       WHERE e.id = ? AND c.teacher_id = ?`,
      [enrollmentId, teacher_id],
      (err, result) => {
        if (err) {
          return res.status(500).json({ error: '数据库查询错误' });
        }
        if (result) {
          return next();
        }
        res.status(403).json({ error: '无权访问该选课记录' });
      }
    );
    return;
  }

  res.status(403).json({ error: '无权访问' });
};

// 学生选课
router.post('/', authenticateToken, async (req, res) => {
  const { role, student_id } = req.user;
  const { course_id } = req.body;

  // 只有学生可以选课
  if (role !== 'student') {
    return res.status(403).json({ error: '只有学生可以选课' });
  }

  // 验证课程是否存在且开放选课
  try {
    const course = await new Promise((resolve, reject) => {
      db.get(
        'SELECT * FROM courses WHERE id = ? AND status = ?',
        [course_id, 'open'],
        (err, result) => {
          if (err) reject(err);
          else resolve(result);
        }
      );
    });

    if (!course) {
      return res.status(400).json({ error: '课程不存在或未开放选课' });
    }

    // 检查是否已经选过这门课
    const existingEnrollment = await new Promise((resolve, reject) => {
      db.get(
        'SELECT * FROM enrollments WHERE student_id = ? AND course_id = ?',
        [student_id, course_id],
        (err, result) => {
          if (err) reject(err);
          else resolve(result);
        }
      );
    });

    if (existingEnrollment) {
      return res.status(400).json({ error: '已经选过这门课程' });
    }

    // 检查课程是否已满
    const enrolledCount = await new Promise((resolve, reject) => {
      db.get(
        'SELECT COUNT(*) as count FROM enrollments WHERE course_id = ?',
        [course_id],
        (err, result) => {
          if (err) reject(err);
          else resolve(result.count);
        }
      );
    });

    if (enrolledCount >= course.max_students) {
      return res.status(400).json({ error: '课程已满' });
    }

    // 检查时间冲突
    const hasTimeConflict = await new Promise((resolve, reject) => {
      db.all(
        `SELECT cs1.* 
         FROM course_schedules cs1
         JOIN course_schedules cs2 ON 
           cs1.day_of_week = cs2.day_of_week AND
           ((cs1.start_time <= cs2.start_time AND cs1.end_time > cs2.start_time) OR
            (cs1.start_time < cs2.end_time AND cs1.end_time >= cs2.end_time) OR
            (cs1.start_time >= cs2.start_time AND cs1.end_time <= cs2.end_time))
         JOIN enrollments e ON cs2.course_id = e.course_id
         WHERE cs1.course_id = ? AND e.student_id = ? AND e.status = 'enrolled'`,
        [course_id, student_id],
        (err, results) => {
          if (err) reject(err);
          else resolve(results.length > 0);
        }
      );
    });

    if (hasTimeConflict) {
      return res.status(400).json({ error: '与已选课程时间冲突' });
    }

    // 创建选课记录
    await new Promise((resolve, reject) => {
      db.run(
        'INSERT INTO enrollments (student_id, course_id, status) VALUES (?, ?, ?)',
        [student_id, course_id, 'enrolled'],
        function(err) {
          if (err) reject(err);
          else resolve(this.lastID);
        }
      );
    });

    res.json({ message: '选课成功' });

  } catch (error) {
    console.error('选课失败:', error);
    res.status(500).json({ error: '选课失败', details: error.message });
  }
});

// 学生退课
router.delete('/:id', authenticateToken, checkEnrollmentAccess, async (req, res) => {
  const { role } = req.user;
  const enrollmentId = req.params.id;

  // 只有学生可以退课
  if (role !== 'student') {
    return res.status(403).json({ error: '只有学生可以退课' });
  }

  try {
    // 检查选课记录状态
    const enrollment = await new Promise((resolve, reject) => {
      db.get(
        'SELECT * FROM enrollments WHERE id = ?',
        [enrollmentId],
        (err, result) => {
          if (err) reject(err);
          else resolve(result);
        }
      );
    });

    if (!enrollment) {
      return res.status(404).json({ error: '选课记录不存在' });
    }

    if (enrollment.status !== 'enrolled') {
      return res.status(400).json({ error: '只能退正在修读的课程' });
    }

    // 更新选课状态为已退课
    await new Promise((resolve, reject) => {
      db.run(
        'UPDATE enrollments SET status = ? WHERE id = ?',
        ['dropped', enrollmentId],
        function(err) {
          if (err) reject(err);
          else resolve(this.changes);
        }
      );
    });

    res.json({ message: '退课成功' });

  } catch (error) {
    console.error('退课失败:', error);
    res.status(500).json({ error: '退课失败', details: error.message });
  }
});

// 获取选课记录详情
router.get('/:id', authenticateToken, checkEnrollmentAccess, (req, res) => {
  const enrollmentId = req.params.id;

  db.get(
    `SELECT 
      e.*,
      c.course_id, c.name as course_name, c.credit, c.semester,
      t.name as teacher_name,
      s.student_id, s.name as student_name
    FROM enrollments e
    JOIN courses c ON e.course_id = c.id
    JOIN teachers t ON c.teacher_id = t.id
    JOIN students s ON e.student_id = s.id
    WHERE e.id = ?`,
    [enrollmentId],
    (err, enrollment) => {
      if (err) {
        return res.status(500).json({ error: '获取选课记录失败', details: err.message });
      }
      if (!enrollment) {
        return res.status(404).json({ error: '选课记录不存在' });
      }
      res.json({ enrollment });
    }
  );
});

// 获取学生的所有选课记录
router.get('/student/:studentId', authenticateToken, (req, res) => {
  const { role, student_id } = req.user;
  const requestedStudentId = parseInt(req.params.studentId);

  // 检查访问权限
  if (role !== 'admin' && student_id !== requestedStudentId) {
    return res.status(403).json({ error: '无权访问该学生的选课记录' });
  }

  db.all(
    `SELECT 
      e.*,
      c.course_id, c.name as course_name, c.credit, c.semester,
      t.name as teacher_name
    FROM enrollments e
    JOIN courses c ON e.course_id = c.id
    JOIN teachers t ON c.teacher_id = t.id
    WHERE e.student_id = ?
    ORDER BY e.enrollment_date DESC`,
    [requestedStudentId],
    (err, enrollments) => {
      if (err) {
        return res.status(500).json({ error: '获取选课记录失败', details: err.message });
      }
      res.json({ enrollments });
    }
  );
});

// 获取课程的所有选课记录
router.get('/course/:courseId', authenticateToken, (req, res) => {
  const { role, teacher_id } = req.user;
  const courseId = parseInt(req.params.courseId);

  // 检查访问权限
  if (role !== 'admin') {
    db.get(
      'SELECT 1 FROM courses WHERE id = ? AND teacher_id = ?',
      [courseId, teacher_id],
      (err, result) => {
        if (err) {
          return res.status(500).json({ error: '数据库查询错误' });
        }
        if (!result) {
          return res.status(403).json({ error: '无权访问该课程的选课记录' });
        }
        fetchEnrollments();
      }
    );
  } else {
    fetchEnrollments();
  }

  function fetchEnrollments() {
    db.all(
      `SELECT 
        e.*,
        s.student_id, s.name as student_name, s.class
      FROM enrollments e
      JOIN students s ON e.student_id = s.id
      WHERE e.course_id = ?
      ORDER BY s.student_id`,
      [courseId],
      (err, enrollments) => {
        if (err) {
          return res.status(500).json({ error: '获取选课记录失败', details: err.message });
        }
        res.json({ enrollments });
      }
    );
  }
});

module.exports = router;
